/**
 * AIE
 */

package com.boot.notes.aop.interceptor;



import com.boot.common.exception.RRException;
import com.boot.modules.app.annotation.Login;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 权限(Token)验证
 *
 * @author mkq
 * @email meikaiqiangTse@qq.com
 * @date 2019-05-29 15:38
 */
@Component
public class LoginInterceptor extends HandlerInterceptorAdapter {


    public static final String MOBILE = "mobile";
    public static final String OPENID = "openid";
    public static final String USER_INFO = "userInfo";
    public static final String USER_ID = "userId";
    public static final String DEPT_ID = "dpetId";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        Login annotation;
        if (handler instanceof HandlerMethod) {
            //获取类上有没有Login注解 如果等于null 获取方法上有没有Login注解
            annotation = ((HandlerMethod) handler).getMethod().getDeclaringClass().getAnnotation(Login.class) != null
                    ? ((HandlerMethod) handler).getMethod().getDeclaringClass().getAnnotation(Login.class)
                    : ((HandlerMethod) handler).getMethodAnnotation(Login.class);
        } else {
            return true;
        }

        if (annotation == null) {
            return true;
        }

        //从header中获取token
        String token = request.getHeader("token");
        //如果header中不存在token，则从参数中获取token
        if (StringUtils.isBlank(token)) {
            token = request.getParameter("token");
        }

        //token为空
        if (StringUtils.isBlank(token)) {
            throw new RRException("token不能为空");
        }

//        TestCenterUser testCenterUser = redisCache.getCacheObject(CacheConstants.TEST_CENTER_OPENID + token);
//
//        HttpContextUtils.getHttpServletRequest().setAttribute(USER_INFO, testCenterUser);
//
//        HttpContextUtils.getHttpServletRequest().setAttribute(OPENID, token);
//
//        HttpContextUtils.getHttpServletRequest().setAttribute(MOBILE, testCenterUser.getMobile());
//
//        HttpContextUtils.getHttpServletRequest().setAttribute(USER_ID, testCenterUser.getUserId());
//
//        HttpContextUtils.getHttpServletRequest().setAttribute(DEPT_ID, testCenterUser.getDeptId());

        return true;
    }
}
